package com.house.keeper.shiro.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.house.keeper.shiro.service.CORSAuthenticationFilter;
import com.house.keeper.shiro.service.MyShiroRealm;
import com.house.keeper.shiro.service.ShiroSession;
import com.house.keeper.shiro.service.UuidSessionIdGenerator;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.mgt.RememberMeManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.Cookie;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 权限配置文件
 * @author zjj
 * @date 2022-05-09
 */
@Configuration //配置spring并启动spring容器（加载spring）
public class ShiroConfig {
    /**
     * 相当于mybatis中的SqlSessionFactoryBean
     * @param securityManager
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);

//        登录
        shiroFilterFactoryBean.setLoginUrl("/login");
//        首页
//        shiroFilterFactoryBean.setSuccessUrl("/index");
//        错误页面，认证不通过
//        shiroFilterFactoryBean.setUnauthorizedUrl("/error/403");
//        页面权限控制
        shiroFilterFactoryBean.setFilterChainDefinitionMap(ShiroFilerMapFactory.shiroFilterMap());

//        自定义拦截器
        Map<String, Filter> customFilterMap = new LinkedHashMap<>();
        customFilterMap.put("corsAuthenticationFilter",new CORSAuthenticationFilter());

        shiroFilterFactoryBean.setFilters(customFilterMap);

        return shiroFilterFactoryBean;
    }

    /**
     * web应用管理配置
     * @param shiroRealm 认证权限控制
     * @param cacheManager cache缓存
     * @param manager 记住cookie缓存
     * @return
     */
    @Bean
    public DefaultWebSecurityManager securityManager(Realm shiroRealm, CacheManager cacheManager, RememberMeManager manager){

        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();

        securityManager.setCacheManager(cacheManager);
        securityManager.setRememberMeManager(manager);//记住cookie
        securityManager.setRealm(shiroRealm);
        securityManager.setSessionManager(sessionManager());
        return securityManager;
    }

    /**
     * 自定义shiro session缓存管理器
     * 可以跨域情况下使用token进行验证
     * 不依赖sessionId
     * @return
     */
    @Bean
    public SessionManager sessionManager(){
//        继承DefaultWebSessionManager后重写了shiro session 进行注册
        ShiroSession shiroSession = new ShiroSession();

        EnterpriseCacheSessionDAO sessionDAO = new EnterpriseCacheSessionDAO();
        sessionDAO.setSessionIdGenerator(new UuidSessionIdGenerator());

        shiroSession.setSessionDAO(sessionDAO);
        return shiroSession;
    }

    /**
     * 加密算法
     * MD5加密
     * 加密1次
     * @return
     */
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();

        hashedCredentialsMatcher.setHashAlgorithmName("MD5");
        hashedCredentialsMatcher.setHashIterations(1);

        return hashedCredentialsMatcher;
    }

    /**
     * 记住我得配置
     *
     * @return
     */
    @Bean
    public RememberMeManager rememberMeManager(){

        Cookie cookie = new SimpleCookie("rememberMe");
        cookie.setHttpOnly(true);//通过js脚本无法读取cookie信息
        cookie.setMaxAge(60*60*24);//保存一天
        CookieRememberMeManager manager = new CookieRememberMeManager();
        manager.setCookie(cookie);
        return manager;
    }

    /**
     * 缓存配置
     * 使用内存缓存
     *
     * @return
     */
    @Bean
    public CacheManager cacheManager(){
        MemoryConstrainedCacheManager cacheManager = new MemoryConstrainedCacheManager();
        return cacheManager;
    }

    /**
     * 配置Realm，用于认证和授权
     * @param hashedCredentialsMatcher 校验密码用到的算法
     * @return
     */
    @Bean
    public AuthorizingRealm shiroRealm(HashedCredentialsMatcher hashedCredentialsMatcher){
        MyShiroRealm shiroRealm = new MyShiroRealm();
        shiroRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return shiroRealm;
    }

    /**
     * 开启shiro方言，能够在页面使用shiro标签
     * @return
     */
    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }

    /**
     * 启用shiro注解
     * @param securityManager
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor(
            SecurityManager securityManager){

        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);

        return advisor;
    }

}
